package com.pcy.codegenerator.controller;

import com.pcy.codegenerator.config.DataSourceContextHolder;
import com.pcy.codegenerator.utils.DataSourceType;
import com.pcy.codegenerator.config.DynamicDataSource;
import com.pcy.codegenerator.entity.DatabaseConn;
import com.pcy.codegenerator.service.GeneratorService;
import com.pcy.codegenerator.utils.PageUtils;
import com.pcy.codegenerator.utils.Query;
import com.pcy.codegenerator.utils.R;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 彭长云
 * @Description: 代码生成controller
 * @date 2020/1/13 17:01
 */
@RestController
public class GeneratorController {
    @Autowired
    private GeneratorService generatorService;

    /**
     * 数据库表
     */
    @RequestMapping("/table/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        PageUtils pageUtil = generatorService.queryList(new Query(params));

        return pageUtil;
    }

    /**
     * 切换数据源
     */
    @RequestMapping("/datasource/update")
    public R updateDataSource(@RequestBody DatabaseConn dc){
        // 配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(dc.getDriverClass());
        dataSource.setJdbcUrl(dc.getUrl());
        dataSource.setUsername(dc.getUsername());
        dataSource.setPassword(dc.getPassword());


        // 添加一个数据源到多数据源中
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
        Map<Object, Object> dataSourceMap = dynamicDataSource.getDataSourceMap();
        dataSourceMap.put(DataSourceType.db1.getDb(), dataSource);
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        // 切换数据源
        DataSourceContextHolder.setDataSource(DataSourceType.db1.getDb());
        return R.ok("切换成功!");
    }

    /**
     * 生成代码
     */
    @RequestMapping("/generatorCode")
    public R code(String tableName,String template){
        String code = generatorService.generatorCode(tableName, template);
        return R.ok().put("code",code);
    }

    /**
     * 下载生成的代码
     */
    @RequestMapping("/downloadCode")
    public void code(String tables, HttpServletResponse response) throws IOException{
        byte[] data = generatorService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
